import { Component, OnInit, forwardRef, Inject, ChangeDetectorRef, ViewChild } from '@angular/core';

import { ModalDirective } from 'ngx-bootstrap/modal';
import { path } from '../../../path.config';
import { masterService } from '../../../../lib/master.service';
import { FileUploader } from '../../../../lib/ng2-file-upload';
import { AppComponent } from '../../../app.component';
import { NzModalService } from 'ng-zorro-antd';
import * as $ from 'jquery';

@Component({
  selector: 'app-invoice-category-management',
  templateUrl: './invoice-category-management.component.html',
  styleUrls: ['./invoice-category-management.component.css'],
  providers: [forwardRef(() => AppComponent)]
})

export class InvoiceCategoryManagementComponent implements OnInit {
  //api
  // 开票分类列表查询
  private searchList = path.invoiceManage.invoiceCateManage.getAllInvoiceCate;
  // 获取全部开票分类
  private getAllList = path.invoiceManage.invoiceCateManage.getAllList;
  // 创建开票分类
  private createInvoiceCate = path.invoiceManage.invoiceCateManage.creatInvoiceCate;
  // 获取优惠政策标识对应关系
  private getPreferentialPolicyList = path.invoiceManage.invoiceCateManage.getPreferentialPolicyList;
  // 获取零税率标识对应关系
  private getZeroTaxMarkList = path.invoiceManage.invoiceCateManage.getZeroTaxMarkList;
  // 获取增值税特殊管理对应关系
  private getTaxSpecialContentList = path.invoiceManage.invoiceCateManage.getTaxSpecialContentList;
  // 获取开票分类详情
  private getInvoiceInfor = path.invoiceManage.invoiceCateManage.getInvoiceInfor;
  // 更新开票分类详情
  private uodateInvoiceInfor = path.invoiceManage.invoiceCateManage.uodateInvoiceInfor;
  // 设置默认开票分类
  private setDefaultInvoiceCate = path.invoiceManage.invoiceCateManage.setDefaultInvoiceCate;
  // 获取默认开票分类
  private getDefaultList = path.invoiceManage.invoiceCateManage.getDefaultList;
  // 上传文件
  private addFileItem = path.imagesUpload.apiUrl;
  // 批量上传开票分类
  private uploadInvoiceCate = path.invoiceManage.invoiceCateManage.uploadInvoiceCate;

  // 获取开票列表
  invoiceSearchList = [];
  invoiceActivity = '';
  IsActivity = false;
  // 获取对应关系
  zeroTaxMarkList = [];
  PreferentialPolicyList = [];
  TaxSpecialContentList = [];

  // 表格列表项数组
  public rows: Array<any> = [];
  // 当前页码
  public page: any = 1;
  // 一共多少页
  public itemsPerPage: number = 10;
  // 分页最多显示的页数
  public maxSize: number = 5;
  // 总页数计数变化时，事件数等于总页数计数
  public numPages: number = 1;
  // 总共的列表项数
  public totalItems: number = 0;
  // 分页器的文本配置
  public localText = {
    firstBtn: '首页',
    lastBtn: '末页',
    previousBtn: '上一页',
    nextBtn: '下一页'
  }
  // 渲染整个表格时需要传入的参数
  public filter = {
    pageSize: this.itemsPerPage,
    pageIndex: this.page,
    name: ''
  }

  // 新建开票分类数据
  public creatInvoiceItem: any = {
    name: '',
    taxClassification: '',
    taxRate: '',
    usePreferentialPolicy: 0,
    zeroTaxMark: 0,
    taxSpecialContent: 0
  };

  // 编辑开票信息获取的对象
  public editInvoiceItem: any = {
    id: '',
    name: '',
    taxClassification: '',
    taxRate: '',
    usePreferentialPolicy: 0,
    zeroTaxMark: 0,
    taxSpecialContent: 0
  };
  // 编辑的ID
  private editId;
  // 默认的开票分类
  public defaultCate: string = '无';
  // 上传excel对象
  public excelUploader: FileUploader = new FileUploader({
    url: this.addFileItem,
    method: 'post',
    itemAlias: 'uploadedFile'
  })
  private btnEnabled: any = 1;
  public item = {
    excelUrl: ''
  };

  // 搜索的时候获取所有开票分类
  getListFunc(categoryName) {
    let urlObject = {
      name: categoryName
    }
    this.IsActivity = true
    this._masterService
      .getData(this.searchList, urlObject)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.invoiceSearchList = res.data;
          this.cdRef.detectChanges();
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息：' + res.errorMessage);
        }
      })
  }
  // 搜索列表中已经选中的商品
  addListFunc(name) {
    this.invoiceActivity = name;
    this.cdRef.detectChanges();
  }
  // 点击搜索按钮的时候，展示搜索出来的数据
  searchFn(name) {
    this.filter.name = name;
    this.onChangeTable();
  }

  // 渲染表格
  onChangeTable = (urlObj?) => {
    if (urlObj) {
      this.filter.pageSize = urlObj.itemsPerPage;
      this.filter.pageIndex = urlObj.page;
    }
    this._masterService
      .getData(this.getAllList, this.filter)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.rows = res.data.items;
          this.rows.forEach((row, i) => {
            row.updatedTime = row.updatedTime * 1000;
            this.zeroTaxMarkList.forEach((optVal, j) => {
              if (row.zeroTaxMark == optVal.id) {
                row.zeroTaxMark = optVal.name;
              }
            })
            this.PreferentialPolicyList.forEach((optVal, k) => {
              if (row.usePreferentialPolicy == optVal.id) {
                row.usePreferentialPolicy = optVal.name;
              }
            })
            this.TaxSpecialContentList.forEach((optVal, t) => {
              if (row.taxSpecialContent == optVal.id) {
                row.taxSpecialContent = optVal.name;
              }
            })
          })    
          this.totalItems = res.data.pagination.totalCount;
          this.itemsPerPage = res.data.pagination.pageSize;
          this.page = parseInt(res.data.pagination.pageIndex);
          this.cdRef.detectChanges();
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息： ' + res.errorMessage);
        }
      })
  }
  // 显示新建开票模态框
  showCreatModel() {
    $('#newInvoiceBox').removeClass('modalBoxHide');
    $('#newInvoiceContainer').removeClass('modalBoxHide');
  }
  // 新建开票分类
  creatInvoiceCate() {
    // 验证输入的信息
    if (!this.creatInvoiceItem.name) {
      this.app.toastWarning('请输入开票分类！');
      return;
    }
    if (!this.creatInvoiceItem.taxClassification) {
      this.app.toastWarning('请输入纳税分类编码！');
      return;
    }
    if (Number(this.creatInvoiceItem.taxRate) > 1 || !(/^\d+(\.\d{1,2})?$/.test(this.creatInvoiceItem.taxRate))) {
      this.app.toastWarning('请重新输入税率，数字范围在0-1之间，且支持两位小数！');
      return;
    }
    // 更新到服务器
    this._masterService
      .postData(this.createInvoiceCate, this.creatInvoiceItem)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.app.toastSuccess('创建成功');
          // 刷新一下表格
          this.onChangeTable();
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息: ' + res.errorMessage)
        }
      });
    // 更新开票分类的列表
    this._masterService
      .getData(this.searchList)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.invoiceSearchList = res.data;
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息：' + res.errorMessage);
        }
      });
    // 清空新建框
    this.creatInvoiceItem = {
      name: '',
      taxClassification: '',
      taxRate: '',
      usePreferentialPolicy: 0,
      zeroTaxMark: 0,
      taxSpecialContent: 0
    };
    $('#newInvoiceBox').addClass('modalBoxHide');
    $('#newInvoiceContainer').addClass('modalBoxHide');
  }
  // 取消新建开票分类
  cancleCreat() {
    $('#newInvoiceBox').addClass('modalBoxHide');
    $('#newInvoiceContainer').addClass('modalBoxHide');
    this.creatInvoiceItem = {
      name: '',
      taxClassification: '',
      taxRate: '',
      usePreferentialPolicy: 0,
      zeroTaxMark: 0,
      taxSpecialContent: 0
    };
  }
  // 显示编辑开票模态框和编辑商品ID
  showEditModel(itemId) {
    this.editId = itemId;
    var idObj = {
      id: itemId
    }
    this._masterService
      .getData(this.getInvoiceInfor, idObj)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.editInvoiceItem = res.data;
          this.onChangeTable();
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息：' + res.errorMessage);
        }
      })
    $('#editInvoiceBox').removeClass('modalBoxHide');
    $('#editInvoiceContainer').removeClass('modalBoxHide');
  }
  // 关闭编辑模态框
  cancleEditModel() {
    $('#editInvoiceBox').addClass('modalBoxHide');
    $('#editInvoiceContainer').addClass('modalBoxHide');
    this.editInvoiceItem = {
      id: '',
      name: '',
      taxClassification: '',
      taxRate: '',
      usePreferentialPolicy: 0,
      zeroTaxMark: 0,
      taxSpecialContent: 0
    };
  }
  // 保存编辑结果
  saveEditResult() {
    // 验证输入的信息
    if (!this.editInvoiceItem.name) {
      this.app.toastWarning('请输入开票分类！');
      return;
    }
    if (!this.editInvoiceItem.taxClassification) {
      this.app.toastWarning('请输入纳税分类编码！');
      return;
    }
    if (Number(this.editInvoiceItem.taxRate) > 1 || !(/^\d+(\.\d{1,2})?$/.test(this.editInvoiceItem.taxRate))) {
      this.app.toastWarning('请重新输入税率，数字范围在0-1之间，且支持两位小数！');
      return;
    }
    // 把数字更新到接口中去
    this._masterService
      .postData(this.uodateInvoiceInfor, this.editInvoiceItem)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.app.toastSuccess('编辑成功');
          this.cancleEditModel();
          this.onChangeTable();
          // init的时候获取开票分类的列表
          this._masterService
            .getData(this.searchList)
            .subscribe((res) => {
              if (res.statusCode == 200) {
                this.invoiceSearchList = res.data;
              } else if (res.statusCode == 401) {
                this.app.logOff();
              } else {
                this.app.toastError('错误信息：' + res.errorMessage);
              }
            });
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息: ' + res.errorMessage)
        }
      });
  }
  // 展示默认分类更改编辑框
  showSetDefault(itemId) {
    this.editId = itemId;
    $('#setDefaultMask').removeClass('modalBoxHide');
    $('#setDefault').removeClass('modalBoxHide');
  }
  // 关闭默认分类更改编辑框
  cancleSetDefault() {
    $('#setDefaultMask').addClass('modalBoxHide');
    $('#setDefault').addClass('modalBoxHide');
  }
  // 设置默认分类
  saveSetDefault() {
    var idObj = {
      id: this.editId
    }
    // 把设置的默认分类ID传给接口
    this._masterService
      .postData(this.setDefaultInvoiceCate, idObj)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          // 从服务器获取默认开票分类并更新至页面
          this._masterService
            .getData(this.getDefaultList)
            .subscribe((res) => {
              if (res.statusCode == 200) {
                if (res.data != null) {
                  this.defaultCate = res.data.name;
                }
                this.onChangeTable();
              } else if (res.statusCode == 401) {
                this.app.logOff();
              } else {
                this.app.toastError('错误信息：' + res.errorMessage);
              }
            })
          this.app.toastSuccess('设置成功');
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息：' + res.errorMessage);
        }
      })
    // 隐藏设置默认分类编辑框
    $('#setDefaultMask').addClass('modalBoxHide');
    $('#setDefault').addClass('modalBoxHide');
  }
  // 显示批量上传编辑框
  showUploadBox1() {
    this.excelUploader.queue = [];
    $('#uploadMask1').removeClass('modalBoxHide');
    $('#upload1').removeClass('modalBoxHide');
  }
  // 取消批量上传编辑框
  cancelUpload1() {
    $('#uploadMask1').addClass('modalBoxHide');
    $('#upload1').addClass('modalBoxHide');
  }
  // 点击上传按钮时触发的函数
  uploadFile1() {
    this.btnEnabled = 0;
    let that = this;
    let thisItem = that.excelUploader.queue[that.excelUploader.queue.length - 1];
    if (thisItem == undefined) {
      this.app.toastWarning("请选择excel文件！");
      return;
    }
    // 上传文件后缀并验证
    let suffix = thisItem.some.name.substr(thisItem.some.name.lastIndexOf('.') + 1)
    if (suffix != 'xlsx') {
      this.app.toastWarning('请上传excel格式文件');
      return;
    }
    thisItem.withCredentials = false;
    // 成功回调
    thisItem.onSuccess = function (response, status, headers) {
      // 上传文件成功
      if (status == 200) {
        // 上传文件后获取服务器返回的数据
        let tempRes = JSON.parse(response);
        that.item.excelUrl = tempRes.data.url[0];
        that.app.toastSuccess('上传成功！');
        that.btnEnabled = 1;
      } else {
        // 上传文件后获取服务器返回的数据错误
        that.app.toastError('上传失败!');
        that.btnEnabled = 1;
      }
    };
    thisItem.onError = function (response, status, headers) {
      // 错误回调
      that.app.toastError('发生了错误！')
      that.btnEnabled = 1;
    };
    thisItem.upload(); // 开始上传
  }
  // 点击确认提交时刷新页面
  saveAdd1() {
    if (!this.excelUploader.queue.length) {
      this.app.toastWarning('请上传用户模板');
      return;
    }
    this._masterService
      .postData(this.uploadInvoiceCate, this.item)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.app.toastSuccess(res.data + '条数据已更新！');
          // 更新分类的列表
          this._masterService
            .getData(this.searchList)
            .subscribe((res) => {
              if (res.statusCode == 200) {
                this.invoiceSearchList = res.data;
              } else if (res.statusCode == 401) {
                this.app.logOff();
              } else {
                this.app.toastError('错误信息：' + res.errorMessage);
              }
            });
          // 去刷新页面
          this.onChangeTable();
          this.cancelUpload1();
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息: ' + res.errorMessage)
          return;
        }
      });
  }
  constructor(public _masterService: masterService,
    public cdRef: ChangeDetectorRef,
    private confirmServ: NzModalService,
    @Inject(forwardRef(() => AppComponent)) public app: AppComponent) { }

  ngOnInit() {
    // init的时候获取分类的列表
    this._masterService
      .getData(this.searchList)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.invoiceSearchList = res.data;
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息：' + res.errorMessage);
        }
      });
    // 获取零税率标识对应关系
    this._masterService
      .getData(this.getZeroTaxMarkList)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.zeroTaxMarkList = res.data.items;
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息：' + res.errorMessage);
        }
      });
    // 获取增值税特殊管理对应关系
    this._masterService
      .getData(this.getTaxSpecialContentList)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.TaxSpecialContentList = res.data.items;
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息：' + res.errorMessage);
        }
      });
    // 获取优惠政策标识对应关系
    this._masterService
      .getData(this.getPreferentialPolicyList)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          this.PreferentialPolicyList = res.data.items;
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息：' + res.errorMessage);
        }
      });
    // 从服务器获取默认开票分类并更新至页面
    this._masterService
      .getData(this.getDefaultList)
      .subscribe((res) => {
        if (res.statusCode == 200) {
          if (res.data != null) {
            this.defaultCate = res.data.name;
          }
          this.onChangeTable();
        } else if (res.statusCode == 401) {
          this.app.logOff();
        } else {
          this.app.toastError('错误信息：' + res.errorMessage);
        }
      })
    // this.onChangeTable();
  }
  
}
